package door.smartlift.top.service.impl;

import door.smartlift.top.common.constant.WxLoginConstant;
import door.smartlift.top.common.utils.CollectionUtil;
import door.smartlift.top.common.utils.HttpRequest;
import door.smartlift.top.dao.WxInfoMapper;
import door.smartlift.top.dao.WxUserMapper;
import door.smartlift.top.domain.WxInfo;
import door.smartlift.top.domain.WxUser;
import door.smartlift.top.domain.WxUserExample;
import door.smartlift.top.exception.MyDefineException;
import door.smartlift.top.service.WxLoginService;
import lombok.extern.slf4j.Slf4j;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 *
 * @author Admin
 * @date 2018/3/29
 */
@Service("wxLoginService")
@Slf4j
public class WxLoginServiceImpl implements WxLoginService {

    @Autowired
    private WxUserMapper wxUserMapper;

    @Autowired
    private WxInfoMapper wxInfoMapper;

    @Override
    public String wxLogin(String code) {

        WxInfo wxInfo=this.wxInfoMapper.selectWxInfo();

        String url="https://" + WxLoginConstant.DOMAIN_API + WxLoginConstant.Login_URL_SUFFIX + "?appid=" +wxInfo.getAppId() + "&secret=" +wxInfo.getSecrect() + "&grant_type=" + WxLoginConstant.GRANT_TYPE + "&js_code=" + code;

        JSONObject json=HttpRequest.sendGet(url);

        if (json.has(WxLoginConstant.RESULT_CODE_KEY)){

            log.error(code + " is invalid code");
            throw new MyDefineException("code错误");
        }

        String openId=json.getString(WxLoginConstant.OPEN_ID_KEY);
        String sessionKey=json.getString(WxLoginConstant.SESSION_KEY);

        WxUserExample wxUserExample=new WxUserExample();
        wxUserExample.createCriteria().andOpenIdEqualTo(openId);

        List<WxUser> wexUsers=this.wxUserMapper.selectByExample(wxUserExample);

        WxUser wxUser=null;

        long currentTime=System.currentTimeMillis();

        if (CollectionUtil.isNotEmpty(wexUsers)){

            wxUser=wexUsers.get(0);

            //session过期时间
            long sessionExpireDate=currentTime + WxLoginConstant.SESSION_ACTIVE_TIME;

            wxUser.setExpireDate(sessionExpireDate);
            wxUser.setSessionKey(sessionKey);
            wxUser.setLoginTime(new Date());

            this.wxUserMapper.updateByPrimaryKeySelective(wxUser);

        }else {

            wxUser=new WxUser();
            wxUser.setOpenId(openId);
            wxUser.setSessionKey(sessionKey);
            wxUser.setExpireDate(currentTime + WxLoginConstant.SESSION_ACTIVE_TIME);
            wxUser.setLoginTime(new Date());

            this.wxUserMapper.insertSelective(wxUser);
        }


        return sessionKey;
    }

    @Override
    public WxUser findWxUserBySessionId(String sessionId) {

        return this.wxUserMapper.selectWxUserBySession(sessionId);
    }
}
